<template>
  <div>
    <Breadcrumb :opt-data="breadcrumbOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="genCommData"
          :custom-empty="true"
          @pageChanged="getGenCommData"
          @sizeChanged="getGenCommData"
          @filterChange="getGenCommData">
          <EmptyContent slot="empty" :opt-data="tableOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog
        title="通用命令已应用协议"
        :visible.sync="showProtocolDialog"
        :close-on-click-modal="false"
        width="1000px"
        center>
        <GenCommCommand v-if="showProtocolDialog" :gen-comm-form="curGenComm"></GenCommCommand>
      </el-dialog>
      <el-dialog
        title="通用命令操作记录"
        :visible.sync="showHistoryDialog"
        :close-on-click-modal="false"
        width="1400px"
        center>
        <OperationLog :dialogTitle=historyTitle :relationId=historyRelationId></OperationLog>
      </el-dialog>
    </PageLayout>
    <examine-dialog :examineDialog=examineDialog :examineTitle=examineTitle @change="submitExamine"/>
  </div>
</template>

<script>
  import {commonConfig} from "@/config/common";
  import {commonString, msgCode} from "@/config/string";
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {routerMeta} from "@/router/routerMeta";
  import {confirmHandle, deepCopyWithJson, messageHandle, downloadExportData} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import genCommTableCfg from "@/config/table/generalCommand";
  import EZTable from '@/components/table/EZTable';
  import GenCommCommand from "./partial/GenCommCommand";
  import OperationLog from "../../operationLog/OperationLog";
  import examineDialog from "../../../components/examineDialog";

  export default {
    name: "GeneralCommand",
    components: {
      EZTable, GenCommCommand, OperationLog, examineDialog
    },
    data() {
      return {
        historyRelationId: '',
        historyTitle: '',
        examineTitle: '',
        routerMeta: routerMeta,
        tableLoading: true,
        tableId: tableIdConfig.generalCommand,
        tableHdl: null,
        genCommData: [],
        curGenComm: {},
        examineForm: {},
        examineId: '',
        showProtocolDialog: false,
        showHistoryDialog: false,
        examineDialog: false
      }
    },
    computed: {
      breadcrumbOptData() {
        return [
          {
            type: 'btn',
            label: '导出数据',
            icon: 'icon-zujiantubiao-daochu',
            callback: () => {
              this.exportGeneralCommand();
            }
          },
          {
            type: 'btn',
            label: '新增命令',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          },
        ];
      },
      tableOptData() {
        return [
          {
            type: 'btn',
            label: '新增通用命令',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      },
    },
    activated() {
      this.initTableConfig();
      this.getGenCommData();
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, genCommTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const genComm = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.$router.push({
                name: routerMeta.generalCommandEdit.name,
                params: {gid: genComm._id}
              });
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteGeneralCommand(genComm);
              break;
            case tableOptBtnConfig.protocol.type:
              const {
                _id, deviceTypeName = '', generalCommandType: genCommType,
                methodName = '', methodAlias = '', remarks = ''
              } = genComm;
              const commandType = commonConfig.commandType.find(type => type.value === genCommType) || {};
              this.curGenComm = {
                genCommId: _id,
                deviceType: deviceTypeName,
                genCommType: commandType.label || commonString.unknown,
                methodName: methodName,
                methodAlias: methodAlias,
                remarks: remarks,
              };
              this.showProtocolDialog = true;
              break;
            case tableOptBtnConfig.review.type:
              this.examineForm._id = genComm._id;
              this.examineForm.deviceType = genComm.deviceType;
              this.examineForm.methodName = genComm.methodName;
              this.examineTitle = `审核通用命令 - ${genComm.methodName}`
              this.examineDialog = true;
              // this.changeExamineStatus(genComm);
              break;
            case tableOptBtnConfig.history.type:
              this.showHistoryDialog = true;
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      clickCreateBtn() {
        this.$router.push({name: routerMeta.generalCommandAdd.name});
      },
      submitExamine(examineInfo) {
        if (!examineInfo.examineText) {
          this.examineDialog = false;
          return
        }
        const param = {
          ...this.examineForm,
          examineStatus: examineInfo.examineStatus,
          examineText: examineInfo.examineText
        };
        try {
          API.genCommand.genCommEdit(param).then(result => {
            messageHandle({code: msgCode.EDIT_SUCCESS, title: '通用命令'});
            this.examineDialog = false;
            this.getGenCommData();
            this.resetModelForm();
          });
        } catch (e) {
          console.log(e)
        }
      },
      getGenCommData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.genCommand.genCommList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          const assembleParamsText = (src = []) => {
            const destArray = [];
            // 前端数据展示渲染
            src.forEach(s => {
              const key = `key: <span class="font-color-success">${s.paramKey || '--'}</span>`;
              const alias = `, alias: <span class="font-color-success">${s.paramAlias || '--'}</span>`;
              const storeKey = s.storeKey ? `, storeKey: <span class="font-color-danger">${s.storeKey || '--'}</span>` : '';
              destArray.push(`<span>${key}${alias}${storeKey}</span>`);
            });
            return destArray.join('</br>');
          };
          this.genCommData = data.map(d => {
            this.examineText = d.examineText;
            d.examineStatusHtml = d.examineStatus ? `<span class="font-color-primary">已通过</span>`
              : `<span class="font-color-danger">未通过</span><br> （${d.examineText}）`;
            if (!d.examineText) {
              d.examineStatusHtml = `<span class="font-color-warning">暂未审核</span>`;
            }
            // d.examineStatusHtml = d.examineStatusHtml + d.examineText
            // d.examineStatusHtml = d.examineStatusHtml + (d.examineStatus ? '' : `<br>${d.examineText}`)
            return {
              ...d,
              isGeneralText:d.generalProtocol.length>0?`<span class="font-color-danger">是</span>`:`<span class="font-color-primary">否</span>`,
              statusParamsText: assembleParamsText(d.statusParams),
              controlParamsText: assembleParamsText(d.controlParams),
            }
          });
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      deleteGeneralCommand(genComm = {}) {
        confirmHandle({label: `确定要删除通用命令：${genComm.methodAlias} 吗?`}).then(() => {
          if(genComm.generalProtocol.length>0){
            messageHandle({code: msgCode.DELETE_ERROR, title: '通用命令已关联通用协议，无法删除'});
            return
          }
          API.genCommand.genCommDelete({_id: genComm._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '通用命令'});
            this.tableHdl.judgeTableMatched();
            this.getGenCommData();
          });
        }).catch(() => {
        });
      },
      // 审核相关暂不可用 已重写，废弃！ 2022年06月29日10:53:24 By Nick
      changeExamineStatus(genComm = {}) {
        const examineText = genComm.examineStatus ? '驳回审核' : '通过审核';
        confirmHandle({label: `确定要${examineText} - 通用命令：${genComm.methodAlias} 吗？`}).then(() => {
          const param = {
            _id: genComm._id,
            method: genComm.methodName,
            examineStatus: !genComm.examineStatus,
            examineText: this.examineText
          };
          API.genCommand.genCommEdit(param).then(result => {
            messageHandle({code: msgCode.EDIT_SUCCESS, title: '通用命令'});
            this.getGenCommData();
            this.resetModelForm();
          });
        }).catch(() => {
        });
      },
      exportGeneralCommand() {
        confirmHandle({label: `确定全量导出通用命令 ？`}).then(() => {
          API.genCommand.genCommExport().then(result => {
            downloadExportData(result.data, 'generalCommandData.xlsx');
          });
        }).catch(() => {
        });
      },
    },
  }
</script>

<style scoped>

</style>
